<?php
/**
 * @version : 1.0
 * @package : lib/struct
 * @name :  CSystem
 * @todo:  Lớp  cơ sở CSystem. ==> ????
*/
class CSystem
{
  /**
   * Default cache
   *
   * @var CCache
   */
	static $cache;

	/**
	 * Data cache
	 *
	 * @var CCache
	 */
	static $cachedata;

	/**
	 * Layout cache
	 *
	 * @var CCache
	 */
	static $cachelayout;

	/**
	 * Session cache
	 *
	 * @var CCache
	 */
	static $cachesession;

	/**
	 * @var String
	 */
	static $layout_cache_dir;

	/**
	 * @var String
	 */
	static $form_cache_dir;
	
	/**
	 * Config cache
	 *
	 * @var Array
	 */
	static $config_cache_dir;

	static function start()
	{
		if(request('url_mode') == 'ajax') {
			CUrl::$mode = 'ajax';
		}

		$host = @$_SERVER['HTTP_HOST'];
		require_once(ROOT_DIR.'lib/utils/CEstore.php');
		CPortal::$estore_id = 'vict';
		//if ($host!='') {
		if (isset($GLOBALS['host_list'][$host])) {
			if ($estore_id = @$GLOBALS['host_list'][$host]) {
				CPortal::$estore_id = $estore_id;
				$_POST['portal'] = 'estore';
				$_POST['estore_id'] = $estore_id;
			}
		}

		if(DEBUG) {
			require_once ROOT_DIR.'lib/utils/CLog.php';
			error_reporting(E_ALL | E_STRICT | E_NOTICE);
			CLog('SYSTEM','Start up!');
		} else {
			error_reporting(E_ALL);
		}


		self::init_cache();
		if(!(CPortal::$components = CSystem::$cache->get('CPortal::$components')) or DEBUG) {
			require_once ROOT_DIR.'lib/utils/CComponent.php';
			CPortal::$components = CComponent::make_component_cache();
		}
		CSystem::init_portal();
		if(portal()->setting('default-portal')) {
			CPortal::$default = portal()->setting('default-portal');
		}

		self::init_database();
		/*if (request('portal')=='estore') {
  		if (request('estore_id')) {
  			$e = CEstore::getInstance();
  		}
		}*/

		if(!portal()->setting('no-ftp') and $ftp = portal()->setting('ftp'))
		{
			define('USE_FTP',true);
			define('FTP_USER',$ftp['user']);
			define('FTP_PASSWORD',$ftp['password']);
			define('FTP_HOST',$ftp['host']);
			define('FTP_PREFIX','ftp://'.FTP_USER.':'.FTP_PASSWORD.'@'.FTP_HOST.'/');
			define('FILE_SERVER_URL',$ftp['file-server-url']);
			define('HTTP_RESOURCE',$ftp['http-resource']);
		}
		else
		{
			define('USE_FTP',false);
			define('FTP_USER','');
			define('FTP_PASSWORD','');
			define('FTP_HOST','');
			define('FTP_PREFIX','');
			define('FILE_SERVER_URL','http://mail.visky.vn:8080');
			define('HTTP_RESOURCE','');
		}
		if($image_settings = portal()->setting('image_settings')) {
			define('ASIDO_GD_JPEG_QUALITY',$image_settings['jpeg-quality']);
			define('THUMB_WIDTH',$image_settings['thumb-width']);
			define('THUMB_HEIGHT',$image_settings['thumb-height']);
		}

		//CStore::$default->load_schema('lib/data/system.schema.xml');
		if(portal()->setting('session') == 'memcache') {
			CSession::setInstance( new CMemcacheSession() );
		} else {
			CSession::setInstance( new CSession() );
		}
		//Khoanb Edit 29.08.09
		if(class_exists('CLanguage')){
			CLanguage::$current = new CLanguage(session('language',portal()->setting('language')));
		}		
		if(session('user_id')) {
			if(!isset($_COOKIE['userId']) or session('user_id') != $_COOKIE['userId']) {
				setcookie('userId',session('user_id'), time()+3600, '/','.vict.vn');
			}
			CUser::$current = new CUser(session('user_id'));
		} else if(cookie('saved_password') and request('page')!='sign_in') {
			redirect('sign_in', array('href'=>'/?'.$_SERVER['QUERY_STRING']));
		} else {
			if(isset($_COOKIE['userId'])) {
				setcookie('userId', 'guest', time()+3600, '/','.vict.vn');
				setcookie('shopping-cart-total-items', 0, time()+3600, '/','.vict.vn');
			}
			CUser::$current = new CUser(array('id'=>'guest'));
		}

		require_once(ROOT_DIR.'lib/data/CLookupTable.php');
	}

	static function init_database() {
		if(defined('MASTER_DATABASE_HOST')) {
			$database = array(
				'host'=>constant('MASTER_DATABASE_HOST'),
				'user'=>constant('MASTER_DATABASE_USER'),
				'password'=>constant('MASTER_DATABASE_PASSWORD'),
				'database-name'=>constant('MASTER_DATABASE_NAME'),
				'slave-host'=>constant('SLAVE_DATABASE_HOST'),
				'slave-user'=>constant('SLAVE_DATABASE_USER'),
				'slave-password'=>constant('SLAVE_DATABASE_PASSWORD'),
				'slave-database-name'=>constant('SLAVE_DATABASE_NAME'),
			);
		}
		else
		{
			$database = portal()->settings['database'];
		}

		//CLanguage::$current->import(portal()->path.'lang');
		if(!isset($database['slave-host']))
		{
			if(isset($database['slaves']) and is_array($database['slaves']) and $slaves_count = sizeof($database['slaves'])>0)
			{
				if($slaves_count == 1)
				{
					$i = 'slave';
				}
				else
				{
					srand(time());
					$i = rand(0, $slaves_count - 1);
				}
				$database['slave-host'] = $database['slaves'][$i]['host'];
				$database['slave-user'] = $database['slaves'][$i]['user'];
				$database['slave-password'] = $database['slaves'][$i]['password'];
				$database['slave-database-name'] = $database['slaves'][$i]['database-name'];
			}
			else
			{
				$database['slave-host'] = false;
				$database['slave-user'] = false;
				$database['slave-password'] = false;
				$database['slave-database-name'] = false;
			}
		}
		CStore::$default = new CMySQLStore(
			$database['host'],
			$database['user'],
			$database['password'],
			$database['database-name'],
			$database['slave-host'],
			$database['slave-user'],
			$database['slave-password'],
			$database['slave-database-name']
		);
	}

	static function init_portal()
	{
		if(null === ($portal = @CPortal::$components['PORTAL.'.request('portal', CPortal::$default)]))
		{
			$portal = CPortal::$components['PORTAL.'.CPortal::$default];
		}
		CPortal::$current = CPortal(CPortal::get_xml_data($portal));
		self::$layout_cache_dir = ROOT_DIR.'/publish/'.portal()->id.'/layout/';
		self::$form_cache_dir = ROOT_DIR.'/publish/'.portal()->id.'/form/';
		self::$config_cache_dir = ROOT_DIR.'/publish/'.portal()->id.'/config/';
		
		if (!file_exists(self::$layout_cache_dir)) mkdir(self::$layout_cache_dir, 0777, true);
		if (!file_exists(self::$form_cache_dir)) mkdir(self::$form_cache_dir, 0777, true);
		if (!file_exists(self::$config_cache_dir)) mkdir(self::$config_cache_dir, 0777, true);
	}

	static function end()
	{
		if(DEBUG)
		{
			CLog('SYSTEM','Shut down!');
			CLog()->show();
		}
		if(CFile::$ftp_connection_id)
		{
			ftp_close(CFile::$ftp_connection_id);
		}
		exit();
	}

	static function init_cache()
	{
	  $hasMemcache = function_exists('memcache_connect');
	  $cacheSetting = $GLOBALS['cache'];
	  foreach (array('default', 'data', 'layout', 'session') as $cachename) {
	    $cacheItem = 'cache'.($cachename=='default'?'':$cachename);
  		if (isset($cacheSetting[$cachename]) && @$cacheSetting[$cachename]['type']=='memcache') {
  			$cache = new CMemCache($cacheSetting[$cachename]);
  			if(!$cache->connected_server) {
  				$cache = new CCache($cachename);
  			}
  		} else {
  			$cache = new CCache($cachename);
  		}

  		CSystem::$$cacheItem = $cache;
	  }
	}

	static function using($name) {
		$components = explode('.',$name);
		$file_name = '';
		for($i=0; $i<sizeof($components)-1; $i++) {
			$file_name .= 'packages/'.$components[$i].'/';
		}
		require_once($file_name.'modules/'.$components[$i].'/class.php');
	}
}

function using($name){
	CSystem::using($name);
}
?>
